/*
 * Copyright (c) 2022-2023 cetcclout Co., Ltd All rights reserved.
 * Sensor Adapter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.cetccloud.cimp.adapter.handler.abstracts;

import cn.hutool.core.util.ObjectUtil;
import com.cetccloud.cimp.common.util.SensorStringUtils;

import java.nio.Buffer;

/**
 * @author
 * @apiNote 报文数据解析、转换
 * @date 2022/11/23 14:40
 */
public abstract class AbstractParserHandler extends DtuDataHandler {
    protected String dataType;

    /**
     * 处理来自设备的数据
     */
    @Override
    public void fromDtu(Buffer buffer, Object context) {
        System.out.println("AbstractParserHandler——fromDtu");
        Buffer unpack = this.unpack(buffer, (String)context);

        if (SensorStringUtils.startsWith("ENV_DATA", this.dataType)){
            // 环境监测数据模型数据
            nextFromDtuHandler.fromDtu(unpack, context);
        }else {
            this.fromDtuAT(unpack, context);
        }
    }

    /**
     * 处理来自设备查询返回信息
     */
    @Override
    public void fromDtuAT(Buffer buffer, Object context) {
        nextFromDtuHandler.fromDtuAT(buffer, context);
    }

    /**
     * 处理发往设备的数据
     */
    @Override
    public void toDtu(Buffer buffer, Object dtuId) {
        System.out.println("AbstractParserHandler——toDtu");
        Buffer pack = this.pack(buffer, (String)dtuId);
        if(ObjectUtil.isNotEmpty(pack)){
            nextToDtuHandler.toDtu(pack, dtuId);
        }

    }

    /**
     * 设备报文转换为系统报文
     */
    public abstract Buffer unpack(Buffer buffer, String dtuId);

    /**
     * 系统报文转换为设备报文
     */
    public abstract Buffer pack(Buffer buffer, String dtuId);

    /**
     * 初始化报文转换配置
     */
    public abstract void init(String tableName);
}
